package com.iflytek.sbd.demo.lambda.bokedemo;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;

/**
 * @program: sbd
 * @description:
 * @author: 陈英俊
 * @create: 2022-01-21 09:37
 */
public class Demo {

    public static void main(String[] args) throws Throwable {

        List<Person> personList = new ArrayList<>();
        personList.add(new Person("Tom", 8900, "male", "New York"));
        personList.add(new Person("Jack", 7000, "male", "Washington"));
        personList.add(new Person("Lily", 7800, "female", "Washington"));
        personList.add(new Person("Anni", 8200, "female", "New York"));
        personList.add(new Person("Owen", 9500, "male", "New York"));
        personList.add(new Person("Alisa", 7900, "female", "New York"));


        /**
         * 当Optional是空的时候,
         * orElse会执行，返回orElse的结果
         * orElseGet会执行,返回orElseGet的结果
         *
         * 当Optional不是空的时候
         * orElse会执行,返回Optional的结果
         * orElseGet不会执行,返回Optional的结果
         *
         * 结论:
         * 不论Optional是否为空,orElse都是执行
         * 只有Optional是空的是偶,orElseGet才会执行
         *
         *
         * orElseThrow 返回的Optional是空,直接抛出异常
         */
        Person person1 = personList.stream().filter(person -> person.getSalary() > 9000).findFirst().orElse(send());
        System.out.println(person1);
        Person person2 = personList.stream().filter(person -> person.getSalary() > 19000).findFirst().orElseGet(Demo::send);
        System.out.println(person2);
        Person person3 = personList.stream().filter(person -> person.getSalary() > 19000).findFirst().orElseThrow((Supplier<Throwable>) () -> new NoSuchMethodException("发生异常了"));
        System.out.println(person3);

        // 延申一下,构建Optional的区别 of的时候,为null抛出异常
        Optional<Object> o = Optional.of(null);
        Optional<Object> o1 = Optional.ofNullable(null);


//      // 此处就是get不到,抛出了异常:NoSuchElementException: No value present
//        Person person2 = null;
//        try {
//            person2 = personList.stream().filter(person -> person.getSalary() > 91000).findFirst().get();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        System.out.println(person2);
//
//        // 匹配任意
        Person person = personList.stream().filter(p -> p.getSalary() > 19000).findAny().get();

    }


    /**
     * 此方法为了校验findFirst找到值,orElse会不会执行
     *
     * @return
     */
    private static Person send() {
        System.out.println("指定值方法执行了");
        return new Person();
    }
}